<template>
  <div :id="id"  :style="{ height:height,width:width }" />
</template>

<script>
import echarts from "echarts";
export default {
  props: {
    id: {
      type: String,
      default: "chart"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "260px"
    },
    data: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: "阅读数占比分析"
    }
  },
  data() {
    return {
      chart: null,
      legendData:[],
      echartData:[]
    };
  },
  mounted() {
    this.getlegendData()
    this.initChart();
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart = null;
  },
  methods: {
    getlegendData(){
     if(this.data.length === 0){
         return
     }
     this.legendData = []
     this.data.forEach((item,index)=>{
         this.legendData.push(item.name)
     })
    },
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id));
      const option = {
        title: {
                text: this.title,
                left: 'center',
                top: '55%',
                textStyle: {
                    fontSize: 14,
                    fontWeight:400,
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                top: '10%',
                type: 'scroll',
                left: 'center',
                textStyle: { //图例文字的样式
                    fontSize: 12
                },
                itemWidth: 10,
                itemHeight: 10,
                data: this.legendData,
            },
            series: [{
                type: 'pie',
                name:'占比分析',
                center: ['50%', '60%'],
                radius: ['45%', '60%'],
                // clockwise: false, //饼图的扇区是否是顺时针排布
                avoidLabelOverlap: false,
                label: {
                    normal: {
                        show: false,
                        position: 'outter',
                        formatter: ' {b}\n{d}%',
                    }
                },
                labelLine: {
                    show: false,
                },
                data:this.data
            }],
            color: ['#43c1ff', '#f24d4b', '#ffad3d','#9ccc65']
      };
      this.chart.setOption(option);
    }
  }
};
</script>
<style lang='stylus' scoped>
.chartsClass {
  padding-left: 1.2rem;
}
</style>
</script>